package com.example.graduation.controller.ajax;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.graduation.entity.pojo.User;
import com.example.graduation.service.UserService;
import com.example.graduation.util.MailUtil;
import com.example.graduation.util.Md5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.sql.Timestamp;

/**
 * 执行Ajax脚本的Controller
 *
 * @author Jeffery
 */
@Controller
@RequestMapping("/ajax")
@Api("执行ajax脚本的Controller")
@Slf4j(topic = "AjaxController")
public class AjaxController {
    @Resource
    private UserService userService;
    @Resource
    private MailUtil mailUtil;

    /**
     * 找回密码
     *
     * @param email 用户邮箱
     * @param name  用户名
     * @return html
     */
    @PostMapping("/forgetPassword")
    @ApiOperation("忘记密码")
    public String forgetPassword(@RequestParam("email") String email, @RequestParam("name") String name, Model model) {
        String resultMsg;

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_email", email);
        wrapper.eq("user_username", name);
        User user = userService.getOne(wrapper);
        if (user == null) {
            resultMsg = "邮箱或账户名错误";
            log.error("用户输入信息错误！");
        } else {
            //更新用户密码为默认111111
            resultMsg = "您的默认密码为: 111111";

            //将默认密码转为盐值加密的密码
            String encryptedPwd = Md5Util.getEncryptedPwd("111111");
            user.setPassword(encryptedPwd);
            user.setUpdateTime(new Timestamp(System.currentTimeMillis()));

            userService.updateById(user);
            log.info("密码默认成功！");

            mailUtil.sendMail(email, resultMsg);
            log.info("密码已发送至邮箱!");
        }
        model.addAttribute("forget_msg", resultMsg);
        return "邮箱或账户名错误".equals(resultMsg) ? "forgetPassword" : "index";
    }


}
